package com.blrs.web.oss;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class OosService {
    @Autowired
    private ZosClient zosClient;
    @Value("${zos.oss.bucketName}")
    private String bucketName;
    @Value("${zos.oss.endpoint}")
    private String endPoint;
    @Value("${zos.oss.accessKeyId}")
    private String accessKey;
    @Value("${zos.oss.accessKeySecret}")
    private String secretKey;
    /**
     * @Desecription: 上传文件
     */
    public Map<String,String> uploadFile(MultipartFile file, String fileName) {
        InputStream inputStream = null;
        String pathUrl = "";
        Map<String, String> stringStringMap = new HashMap<>();
        try {
            inputStream = file.getInputStream();
            AmazonS3 ossClient = zosClient.getS3Client();
            String remoteFilePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String path = dir + IdWorker.getIdStr() + suffix;
            String newFileName = IdWorker.getIdStr() + suffix;
            try {
                objectMetadata.setContentLength(inputStream.available());
                // 上传文件
                log.info("开始上传文件到oss");
                log.info("bucket: " + zosClient.getBucketName());
                log.info("path: " + path);
                log.info("inputStream: " + inputStream);
                log.info("objectMetadata: " + objectMetadata);
                PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream,objectMetadata);
                request.setCannedAcl(CannedAccessControlList.PublicRead);
                PutObjectResult result = ossClient.putObject(request);
                log.info("上传结果："+result.getETag());
                //ossClient.putObject(zosClient.getBucketName(), path, inputStream, objectMetadata);
                //URL url = ossClient.generatePresignedUrl(new GeneratePresignedUrlRequest(oosClientConfig.getBucket(), path));
                //String url = generatePresignedUrl(path);
                //手动拼接
                pathUrl = endPoint+"/"+bucketName+"/"+path;
            } catch (Exception e) {
                log.error("上传文件到oos失败", e);
            } finally {
                if (ossClient != null) {
                    ((AmazonS3Client) ossClient).shutdown();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            stringStringMap.put("pathUrl", pathUrl);
            stringStringMap.put("newFileName", newFileName);
            stringStringMap.put("path", path);
            return stringStringMap;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * @Desecription: 删除文件
     */
    public boolean deleteFile(String  filePath) {
        AmazonS3 ossClient = zosClient.getS3Client();

        boolean exist = ossClient.doesObjectExist(zosClient.getBucketName(),filePath);
        if (!exist) {
            log.error("从OSS存储删除的文件不存在,path={}", filePath);
            return false;
        } else {
            try {
                ossClient.deleteObject(zosClient.getBucketName(), filePath);
            } catch (Exception e) {
                log.error("从天翼云OSS删除文件出错,path={}", filePath, e);
                return false;
            } finally {
                if (ossClient != null) {
                    try {
                        ((AmazonS3Client) ossClient).shutdown();
                    } catch (AmazonClientException e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    }

    /**
     * @Desecription: 获取文件下载地址 ,并设置过期时间
     */
    public String generatePresignedUrl(String fileKey) throws ParseException {
        GeneratePresignedUrlRequest request = new
                GeneratePresignedUrlRequest(zosClient.getBucketName(), fileKey);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date expireDate = sdf.parse("2131-01-01");
        request.setExpiration(expireDate);
        URL url = zosClient.getS3Client().generatePresignedUrl(request);
        return url.toString();
    }

    public static boolean isOssResource(String resource) {
        return resource != null && resource.contains("https://bucket-e577.changsha42.zos.ctyun.cn");
    }


}
